#include <fstream>
#include <stdexcept>
#include <json/elements.h>
#include <json/reader.h>
#include "Level.hpp"



Level::Level():
m_startPos(),
m_platforms()
{
}
Level::~Level()
{
    clear();
}
       
void Level::loadFromFile(const std::string& fileName)
{
    std::string path = "media/levels/";
    path += fileName;
    
    std::ifstream file(path.c_str());
    
    if(!file.is_open())
        throw std::runtime_error("failed to open file : " + path);

	// we parse the file
	json::Object root;
	try 
	{
		json::Reader::Read(root,file);
		file.close();
	}
    catch (json::Reader::ScanException& e)
    {
		std::cerr << "Caught json::ScanException : " << e.what() << ", Line/offset: " << e.m_locError.m_nLine + 1 << '/' << e.m_locError.m_nLineOffset + 1 << " in file : " << fileName << std::endl;
        throw std::runtime_error("Error while scanning level file " + fileName + ".");
    }
    catch (json::Reader::ParseException& e)
    {
		std::cerr << "Caught json::ParseException : " << e.what() << ", Line/offset of token begin: " << e.m_locTokenBegin.m_nLine + 1 << '/' << e.m_locTokenBegin.m_nLineOffset + 1 << ", Line/offset of token end: " << e.m_locTokenEnd.m_nLine + 1 << '/' << e.m_locTokenEnd.m_nLineOffset + 1 << " in file : " << fileName << std::endl;
        throw std::runtime_error("Error while parsing level file " + fileName + ".");
    }
    
    // start position
    json::Number &playerx = root["startPos"]["x"];
    json::Number &playery = root["startPos"]["y"];     
    
    m_startPos.x = playerx.Value();
    m_startPos.y = playery.Value();
    
    // platforms
    clear();

    json::Array &platforms = root["platforms"];
    for(unsigned int i = 0; i < platforms.Size(); ++i)
    {
        Platform *p = new Platform();
        p->load(platforms[i]);
        m_platforms.push_back(p);
    }

    // background
}
       

sf::Vector2f Level::startPos() const
{
    return m_startPos;
}


void Level::draw(sf::RenderTarget &target)
{
    // background

    // platforms 
    std::list<Platform*>::iterator itor = m_platforms.begin();
    for(; itor != m_platforms.end(); ++itor)
        target.draw(**itor);
}

void Level::clear()
{
    std::list<Platform*>::iterator itor = m_platforms.begin();
    for(; itor != m_platforms.end(); ++itor)
        delete *itor;
        
   m_platforms.clear();
}

